/**
 * Created with JetBrains WebStorm.
 * User: ROLBACK
 * Date: 11/16/13
 * Time: 7:28 AM
 * To change this template use File | Settings | File Templates.
 */

var com = com || {};
var timer = timer || {};
var bg = bg || {};
var linkTutorial = "http://cohinh.vn";
var typeTotal = 0;
var typeTurn = 1;
var typeMoney = 2;
var typeType = 3;
var settingTotalTime = [600, 900, 1200, 1500, 1800, 3600];
var settingTurnTime = [30, 60, 120, 300, 600, 900];
var settingMoney = [10, 20, 50, 70, 80, 100];

com.init = function () {
    LOG("init chess board");
    com.canvas = document.getElementById('canvas1');
    com.context = com.canvas.getContext('2d');
    com.width = 790;
    com.height = 587;

    com.canvas.width = com.width;
    com.canvas.height = com.height;
    com.lastMovePosX =null;
    com.lastMovePosY =null;
    com.pieceMove = null;
    /*//xac dinh van co da bat dau chua
     com.isPlay = false;
     //mau cua nguoi choi la minh.
     com.myColor = Red;*/
    //xac dinh xem piece da duoc select chua
    com.isSelected = false;
    com.isSetting = false;
    com.score = {};
    //path file dot.png suggest
    com.dot = new Image();
    com.dot.src = "images/dot.png";
    com.radioOn = new Image();
    com.radioOn.src = "images/radio_on.png";
    com.radioOff = new Image();
    com.radioOff.src = "images/radio_off.png";
    com.btnOk = new Image();
    com.btnOk.src = "images/agree.png";
    com.btnCancel = new Image();
    com.btnCancel.src = "images/cancel.png";
    com.settingHeader = new Image();
    com.settingHeader.src = "images/setting_header.png";
    com.settingFooter = new Image();
    com.settingFooter.src = "images/setting_footer.png";
    com.settingRight = new Image();
    com.settingRight.src = "images/setting_right.png";
    com.settingLeft = new Image();
    com.settingLeft.src = "images/setting_left.png";
    com.winImage = new Image();
    com.winImage.src = "images/win.png";
    com.loseImage = new Image();
    com.loseImage.src = "images/lose.png";
    com.box = new Image();
    com.box.src = "images/box.png";
    com.starBlue = new Image();
    com.starBlue.src = "images/star_blue.png";
    com.starRed = new Image();
    com.starRed.src = "images/star_red.png";

    //TODO change setting room
//    com.setting = {};
//    com.setting.totalTime = 600;
//    com.setting.turnTime = 300;
//    com.setting.money = 1000;
//    com.setting.type = 1;

    //draw timer
    initTimer();
    //draw bg
    drawBackground();

    //draw button
    drawButton();
    //khi click vao button start thi se goi den ham nay
    newGame();
}

function updateSetting(){
    com.setting.times = [com.setting.totalTime, com.setting.totalTime, com.setting.turnTime];
    updateTime();
    timer.context.fillStyle = "black";
    timer.context.font = 'bold 15px sans-serif';
    timer.context.fillText(com.setting.point,607, 30);
}

function calculateTime(count){
    var minute = Math.floor(count / 60);
    if (minute < 10) {
        minute = "0" + minute;
    }
    var second = count % 60;
    if (second < 10) {
        second = "0" + second;
    }
    if (count < 10) {
        timer.context.fillStyle = "red";
    }else{
        timer.context.fillStyle = "black";
    }

    return {
        'minute':minute,
        'second':second
    };
}

function updateTime(){
    timer.context.clearRect(0, 0, com.width, com.height);
    var time1 = calculateTime(com.setting.times[0]);
    var time2 = calculateTime(com.setting.times[1]);
    var turnTime = calculateTime(com.setting.turnTime);
    var currentTurnTime = calculateTime(com.setting.times[2]);

    timer.context.font = 'bold 15px sans-serif';
    if(com.canMove){
        timer.context.fillText(currentTurnTime.minute+ ":" + currentTurnTime.second, 602, 455);
        timer.context.fillStyle = "black";
        timer.context.fillText(turnTime.minute + ":" + turnTime.second, 602, 95);
    }else{
        timer.context.fillText(currentTurnTime.minute+ ":" + currentTurnTime.second, 602, 95);
        timer.context.fillStyle = "black";
        timer.context.fillText(turnTime.minute + ":" + turnTime.second, 602, 455);
    }

    timer.context.fillStyle = "red";
    timer.context.font = 'bold 20px sans-serif';
    timer.context.fillText(time2.minute + ":" + time2.second, 595, 172);
    timer.context.fillText(time1.minute + ":" + time1.second, 595, 533);
}

function initTimer() {
    timer.canvas = document.getElementById('time');
    timer.context = timer.canvas.getContext('2d');

    timer.canvas.width = com.width;
    timer.canvas.height = com.height;

    updateSetting();
//    timer.countDown = setInterval(countDownTime, 1000);
}

var count;
function countDownTime() {
    updateTime();
    timer.context.fillStyle = "black";
    timer.context.font = 'bold 15px sans-serif';
    timer.context.fillText(com.setting.point,607, 30);

    if(com.canMove){
        com.setting.times[0]--;
    }else{
        com.setting.times[1]--;
    }

    com.setting.times[2]--;

    if (com.setting.times[0] < 0 || com.setting.times[1] < 0 || com.setting.times[2] < 0) {
        timer.context.fillStyle = "#000000";
        clearInterval(timer.countDown);
        return;
    }
}

function drawBackground() {
    bg.canvas = document.getElementById('background');
    bg.context = bg.canvas.getContext('2d');

    bg.canvas.width = com.width;
    bg.canvas.height = com.height;

    var space = 60;
    var numberSquare = 9;
    var startDraw = 20;
    var endDraw = startDraw + space * numberSquare;
    var startDrawCharacterX = 45;
    var startDrawCharacterY = 55;
    var characterArray = [
        ["A", "B", "C", "D", "E", "F", "G", "H", "I"],
        ["9", "8", "7", "6", "5", "4", "3", "2", "1"]
    ];

    bg.context.lineWidth = 2;
    bg.context.strokeStyle = "#006600";
    bg.context.fillStyle = "#006600";
    bg.context.font = 'bold 15px sans-serif';
    bg.context.beginPath();
    bg.context.rect(1, 1, 780, 580);
    for (var i = 0; i <= numberSquare; i++) {
        bg.context.moveTo(startDraw, startDraw + i * space);
        bg.context.lineTo(endDraw, startDraw + i * space);

        bg.context.moveTo(startDraw + i * space, startDraw);
        bg.context.lineTo(startDraw + i * space, endDraw);
        if (i < 9) {
            bg.context.fillText(characterArray[1][i], 7, startDrawCharacterY + i * space);
            bg.context.fillText(characterArray[0][i], startDrawCharacterX + i * space, 575);
        }
    }

    drawCellBoard();
    drawScoreTable();
    if (com.myColor == Blue) {
        drawAvatar(false, null);
    } else if (com.myColor == Red) {
        for(var i = 0; i<com.listUser.length; i++){
            if(com.listUser[i].name != com.myProfile.name){
                drawAvatar(true, com.listUser[i]);
                break;
            }
        }
    }

    //draw watch
    bg.watch = new Image();
    bg.watch.src = "images/watch.png";
    bg.watch.onload = function () {
        bg.context.drawImage(bg.watch, 573, 45);
        bg.context.drawImage(bg.watch, 573, 405);
    };

    //draw bet money
    bg.money = new Image();
    bg.money.src = "images/money.png";
    bg.money.onload = function(){
        bg.context.drawImage(bg.money, 573, 10);
    }

    bg.context.fillStyle = "#76797C";
    bg.context.fillRect(573, 145, 95, 40);
    bg.context.fillRect(573, 505, 95, 40);
    bg.context.fillStyle = "#006600";
    bg.context.stroke();
}

//draw chess board
function drawButton() {
    initGButton(0);
    if(com.myColor==Blue){
        drawStartButton();
    }else{
        drawReadyButton();
    }
    com.buttonSetting = new Image();
    com.buttonGuide = new Image();
    com.buttonExit = new Image();
    com.buttonSetting.src = "images/btn_setting.png";
    com.buttonGuide.src = "images/btn_guide.png";
    com.buttonExit.src = "images/btn_exit.png";

    com.buttonSetting.onload = function () {
        com.context.drawImage(com.buttonSetting, 573, 210);
    };

    com.buttonGuide.onload = function () {
        com.context.drawImage(com.buttonGuide, 573, 270);
    };

    com.buttonExit.onload = function () {
        com.context.drawImage(com.buttonExit, 573, 330);
    };

    com.canvas.addEventListener("click", boardClick, false);
}

function initGButton(pos) {
    //draw G button
    com.gBlue = new Image();
    com.gRed = new Image();
    com.gBlue.src = "images/blue_g.png";
    com.gRed.src = "images/red_g.png"
    com.gBlue.onload = function () {
        com.score.blue = 0;
        drawGButton(Blue, 0, 0);
    };
    com.gRed.onload = function () {
        com.score.red = 0;
        drawGButton(Red, 0, 0);
    };
}

function drawGButton(color, pos, point) {
    if(pos>=15){
        pos = 15;
    }
    if (color == Blue) {
        if (com.myColor == Blue) {
            com.context.clearRect(698, 114, 22, 352);
            if(com.winRound1==Blue || com.winRound2==Blue){
                com.context.drawImage(com.starBlue, 698, 444 - pos * 22);
            }else{
                com.context.drawImage(com.gBlue, 698, 444 - pos * 22);
            }
            if((pos-point)>0){
                com.context.drawImage(com.box, 700, (446 - (pos-point)*22), 18, 18);
            }
        } else if (com.myColor == Red) {
            com.context.clearRect(720, 114, 22, 352);
            if(com.winRound1==Blue || com.winRound2==Blue){
                com.context.drawImage(com.starBlue, 720, 114 + pos * 22);
            }else{
                com.context.drawImage(com.gBlue, 720, 114 + pos * 22);
            }
            if((pos-point)>0){
                com.context.drawImage(com.box, 722, (116 + (pos-point)*22), 18, 18);
            }
        }
    } else if (color == Red) {
        com.context.clearRect(com.gRed.x, com.gRed.y, com.gRed.width, com.gRed.height);
        if (com.myColor == Red) {
            com.context.clearRect(698, 114, 22, 352);
            if(com.winRound1==Red || com.winRound2==Red){
                com.context.drawImage(com.starRed, 698, 444 - pos * 22);
            }else{
                com.context.drawImage(com.gRed, 698, 444 - pos * 22);
            }

            if((pos-point)>0){
                com.context.drawImage(com.box, 700, (446 - (pos-point)*22), 18, 18);
            }
        } else if (com.myColor == Blue) {
            com.context.clearRect(720, 114, 22, 352);
            if(com.winRound1==Red || com.winRound2==Red){
                com.context.drawImage(com.starRed, 720, 114 + pos * 22);
            }else{
                com.context.drawImage(com.gRed, 720, 114 + pos * 22);
            }

            if((pos-point)>0){
                com.context.drawImage(com.box, 722, (116 + (pos-point)*22), 18, 18);
            }
        }
    }
}

function drawAvatar(isTop, user) {
    //draw two avatar
    if(!isTop){
        user = com.myProfile;
    }

    bg.avatar = new Image();
    bg.avatar.src = "images/avatar_default.png";
    bg.avatar.onload = function(){
        bg.context.drawImage(bg.avatar, 680, 480);
        if (isTop) {
            bg.context.drawImage(bg.avatar, 680, 20);
            drawMoney(false, com.myProfile.getVariable("variables").value.point);
            drawMoney(true, user.getVariable("variables").value.point);
        }else{
            drawMoney(false, com.myProfile.getVariable("variables").value.point);
        }
    }

    if(isTop){
        drawHonourable(com.myProfile, false);
        drawHonourable(user, true);
        drawName(false, com.myProfile.name);
        drawName(true, user.name);
    }else{
        drawHonourable(user, false);
        drawName(false, com.myProfile.name);
    }

    bg.context.rect(680, 20, 80, 80);
    bg.context.rect(680, 480, 80, 80);
}

function drawAvatarReady(isTop, user){
    if(!isTop){
        user = com.myProfile;
    }

    bg.avatar = new Image();
    bg.avatar.src = "images/avatar_default.png";
    bg.avatar.onload = function(){
        bg.context.drawImage(bg.avatar, 680, 480);
        if (isTop) {
            bg.context.drawImage(bg.avatar, 680, 20);
            drawMoney(false, com.myProfile.getVariable("variables").value.point);
            drawMoney(true, user.getVariable("variables").value.point);
        }else{
            drawMoney(false, com.myProfile.getVariable("variables").value.point);
        }
        drawReady(isTop);
    }

    if(isTop){
        drawHonourable(com.myProfile, false);
        drawHonourable(user, true);
        drawName(false, com.myProfile.name);
        drawName(true, user.name);
    }else{
        drawHonourable(user, false);
        drawName(false, com.myProfile.name);
    }

    bg.context.rect(680, 20, 80, 80);
    bg.context.rect(680, 480, 80, 80);

}

function drawMoney(isTop, money){
    bg.context.fillStyle = "red";
    bg.context.font = '15px sans-serif';
    var width = bg.context.measureText(money).width;
    var startX = 720-width/2;
    if(isTop){
        bg.context.fillText(money, startX, 97);
    }else{
        bg.context.fillText(money, startX, 558);
    }
    bg.context.fillStyle = "#006600";
    bg.context.font = 'bold 15px sans-serif';
}

function drawName(isTop, name){
    bg.context.fillStyle = "#000000";
    bg.context.font = 'bold 20px sans-serif';
    var width = bg.context.measureText(name).width;
    var startX = 720-width/2;
    LOG("width text: "+width+", startX: "+startX);
    if(isTop){
        bg.context.fillText(name, startX, 17);
    }else{
        bg.context.fillText(name, startX, 578);
    }
    bg.context.fillStyle = "#006600";
    bg.context.font = 'bold 15px sans-serif';
}

function drawReady(isTop){
    bg.context.fillStyle = "red";
    bg.context.font = 'bold 18px sans-serif';
    var ready = "sẵn sàng";
    var width = bg.context.measureText(ready).width;
    var startX = 720-width/2;
    LOG("width text: "+width+", startX: "+startX);
    if(isTop){
        bg.context.fillText(ready, startX, 57);
    }else{
        bg.context.fillText(ready, startX, 538);
    }
    bg.context.fillStyle = "#006600";
    bg.context.font = 'bold 15px sans-serif';
}

function drawHonourable(user, isTop){
    bg.honourable = new Image();
    var variable = user.getVariable("variables").value;
    if(variable.honourable==1){
        bg.honourable.src = "images/bronze.png";
    }else if(variable.honourable==2){
        bg.honourable.src = "images/silver.png";
    }else if(variable.honourable==3){
        bg.honourable.src = "images/gold.png";
    }

    bg.honourable.onload = function () {
        if (isTop) {
            bg.context.drawImage(bg.honourable, 730, 20, 30, 30);
        }else{
            bg.context.drawImage(bg.honourable, 730, 480, 30, 30);
        }
    };
}

function removeAvatar() {
    bg.context.clearRect(680, 2, 80, 100);
    bg.context.fillStyle = "#006600";
    bg.context.rect(680, 20, 80, 80);
    bg.context.stroke();
}

function userLeaveRoom(){
    com.myColor = Blue;
    com.isPlay = false;
    drawButton();
    newGame();
}

function drawScoreTable() {
    //draw score table of player
    bg.context.rect(698, 114, 44, 352);
    bg.context.moveTo(720, 114);
    bg.context.lineTo(720, 466);
    bg.context.moveTo(720, 114);
    bg.context.lineTo(742, 136);
    bg.context.moveTo(742, 114);
    bg.context.lineTo(720, 136);
    bg.context.moveTo(698, 444);
    bg.context.lineTo(720, 466);
    bg.context.moveTo(720, 444);
    bg.context.lineTo(698, 466);

    var pointArray = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"];
    var startDraw = 136;
    var space = 22;
    bg.context.font = 'bold 10px sans-serif';
    for (var i = 0; i < pointArray.length; i++) {
        if (i < 15) {
            bg.context.moveTo(698, startDraw + i * space);
            bg.context.lineTo(742, startDraw + i * space);
        }

        if(i==0){
            bg.context.fillStyle = "red";
            bg.context.fillText(pointArray[pointArray.length - i - 1], 680, (startDraw - 5) + i * space);
            bg.context.fillStyle = "#006600";
            bg.context.fillText(pointArray[i], 750, (startDraw - 5) + i * space);
        }else if(i==5||i==10){
            bg.context.fillStyle = "red";
            bg.context.fillText(pointArray[pointArray.length - i - 1], 680, (startDraw - 5) + i * space);
            bg.context.fillText(pointArray[i], 750, (startDraw - 5) + i * space);
            bg.context.fillStyle = "#006600";
        }else if(i==15){
            bg.context.fillStyle = "red";
            bg.context.fillText(pointArray[i], 750, (startDraw - 5) + i * space);
            bg.context.fillStyle = "#006600";
            bg.context.fillText(pointArray[pointArray.length - i - 1], 680, (startDraw - 5) + i * space);
        }else{
            bg.context.fillText(pointArray[pointArray.length - i - 1], 680, (startDraw - 5) + i * space);
            bg.context.fillText(pointArray[i], 750, (startDraw - 5) + i * space);
        }
    }
}

function drawCellBoard() {
    for (var i = 0; i < 9; i++) {
        for (var j = 0; j < 9; j++) {
            if ((i % 2 == 0 && j % 2 == 1) || (i % 2 == 1 && j % 2 == 0)) {
                var pos = getPosOfCell(i, j);
                bg.context.fillRect(pos.x, pos.y, 60, 60);
            }
        }
    }
}

function drawHighLight(lo){
    bg.context.fillStyle = "#fefe00";
    var pos = getPosOfCell(lo.x, lo.y);
    bg.context.fillRect(pos.x, pos.y, 60, 60);
}

function removeHighLight(lo){
    var pos = getPosOfCell(lo.x, lo.y);
    bg.context.fillStyle = "#006600";
    bg.context.clearRect(pos.x, pos.y, 60, 60);
    if((lo.x % 2 == 0 && lo.y % 2 == 1) || (lo.x% 2 == 1 && lo.y % 2 == 0)){
        bg.context.fillRect(pos.x, pos.y, 60, 60);
    }
}

function getPosOfCell(i, j) {
    var x = 20 + i * 60;
    var y = 20 + j * 60;
    return {
        'x': x,
        'y': y
    };
}

function drawStartButton() {
    com.startButton = new Image();
    com.startButton.src = "images/start.png";
    com.startButton.onload = function () {
        LOG("draw start button");
        com.context.drawImage(com.startButton, 245, 260);
    }
}

function drawReadyButton() {
    com.ready = new Image();
    com.ready.src = "images/ready.png";
    com.ready.onload = function () {
        LOG("draw start button");
        com.context.drawImage(com.ready, 245, 260);
    }
}

function newGame() {
    com.isReady = false;
    com.winRound1 = null;
    com.winRound2 = null;
    com.pieces = [new Piece(com.canvas, com.context, 1, Blue, com.myColor),
        new Piece(com.canvas, com.context, 2, Blue, com.myColor),
        new Piece(com.canvas, com.context, 3, Blue, com.myColor),
        new Piece(com.canvas, com.context, 4, Blue, com.myColor),
        new Piece(com.canvas, com.context, 5, Blue, com.myColor),
        new Piece(com.canvas, com.context, 6, Blue, com.myColor),
        new Piece(com.canvas, com.context, 7, Blue, com.myColor),
        new Piece(com.canvas, com.context, 8, Blue, com.myColor),
        new Piece(com.canvas, com.context, 9, Blue, com.myColor),
        new Piece(com.canvas, com.context, 1, Red, com.myColor),
        new Piece(com.canvas, com.context, 2, Red, com.myColor),
        new Piece(com.canvas, com.context, 3, Red, com.myColor),
        new Piece(com.canvas, com.context, 4, Red, com.myColor),
        new Piece(com.canvas, com.context, 5, Red, com.myColor),
        new Piece(com.canvas, com.context, 6, Red, com.myColor),
        new Piece(com.canvas, com.context, 7, Red, com.myColor),
        new Piece(com.canvas, com.context, 8, Red, com.myColor),
        new Piece(com.canvas, com.context, 9, Red, com.myColor)];

    com.status = [
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1]
    ];
}

function reInitGame(){
    com.isReady = false;
    com.winRound1 = null;
    com.winRound2 = null;

    for(var i = 0; i<com.pieces.length; i++){
        com.pieces[i].initLocation();
        com.pieces[i].drawPiece();
    }

    com.status = [
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 1]
    ];
}

function boardClick(e) {
    var mousePost = getCursorPosition(e);

    if (mousePost.x == 9 || mousePost.x == 10) {
        if (mousePost.y == 4) {
            //show game tutorial
            window.open(linkTutorial);
        } else if (mousePost.y == 5) {
            //leave room game and come back lobby room
            if (confirm("Do you want to left me now?")) {
                joinLobbyRoom();
            } else {
                //do nothing
            }
        }
    }

    //handle setting click
    if (com.isSetting) {
        var mouseClick = getMouseClickPosition(e);
        radioClick(mouseClick);
        return;
    }

    if (com.isPlay) {
        LOG("game is playing");
        if (cellContainPiece(mousePost)) {
            if (!com.canMove) {
                return;
            }

            //remove all suggest when click
            if (com.listLocation != null) {
                removeAllSuggest(com.listLocation);
                com.listLocation = null;
            }
            com.piece = getPieceAtLocation(mousePost);
            if (com.piece.color == com.myColor) {
                com.listLocation = com.piece.getAllCellCanMove();
                drawSuggest(com.listLocation);
                com.isSelected = true;
                LOG("Piece has selected: " + com.piece.numbers + " pieceId: " + com.piece.idPiece);
            } else {
                com.piece = null;
                com.isSelected = false;
                LOG("can not select this piece!!!");
            }
        } else if (com.isSelected && canMoveTo(mousePost)) {
            if (com.piece != null) {
                LOG("Piece != null: " + com.piece.numbers);
                var params = {};
                params.pieceId = com.piece.idPiece;
                var pSrc = changePosClientToServer(com.piece.mLocation, com.myColor);
                LOG("piece location: " + com.piece.mLocation.x + ", " + com.piece.mLocation.y);
                LOG("pSrc location: " + pSrc.x + ", " + pSrc.y);
                var pDes = changePosClientToServer(mousePost, com.myColor);
                params.posX = pSrc.x;
                params.posY = pSrc.y;
                params.desX = pDes.x;
                params.desY = pDes.y;
                sfs.send(new SFS2X.Requests.System.ExtensionRequest(command.move, params));
                removeAllSuggest(com.listLocation);
                com.listLocation = null;
//                com.piece.movePiece(mousePost);
                com.isSelected = false;
                com.piece = null;
            } else {
                LOG("Piece selected null");
            }
        }
    } else {
        LOG("game's not ready!!!");
        if ((mousePost.x == 5 || mousePost.x == 3 || mousePost.x == 4) && mousePost.y == 4) {
            if (!com.isSetting && com.myColor==Blue && !com.isPlay) {
                LOG("send start game request");
                var param = {};
                sfs.send(new SFS2X.Requests.System.ExtensionRequest(command.start, param));
            } else if (!com.isSetting && com.myColor==Red && !com.isReady) {
                LOG("send start game request");
                var param = {};
                sfs.send(new SFS2X.Requests.System.ExtensionRequest(command.ready, param));
            }
        }
        if ((mousePost.x == 9 || mousePost.x == 10) && mousePost.y == 3) {
            //show dialog setting here
            if (!com.isSetting && com.myColor == Blue) {
                drawSetting();
            }
        }
    }
}

function canMoveTo(lo) {
    if (com.listLocation == null) {
        return false;
    }
    for (var i = 0; i < com.listLocation.length; i++) {
        if (lo.x == com.listLocation[i].x && lo.y == com.listLocation[i].y) {
            return true;
        }
    }
    return false;
}

function removeAllSuggest(arrayLocation) {
    for (var i = 0; i < arrayLocation.length; i++) {
        var pos = getPositionFromLocation(arrayLocation[i]);
        com.context.clearRect(pos.x, pos.y, com.dot.width, com.dot.height);
//        if ((arrayLocation[i].x % 2 == 0 && arrayLocation[i].y % 2 == 1) || (arrayLocation[i].x % 2 == 1 && arrayLocation[i].y % 2 == 0)) {
//            com.context.fillRect(pos.x, pos.y, com.dot.width, com.dot.height);
//        }
    }
}

function drawSuggest(arrayLocation) {
    for (var i = 0; i < arrayLocation.length; i++) {
        var pos = getPositionFromLocation(arrayLocation[i]);
        com.context.drawImage(com.dot, pos.x, pos.y);
    }
}

var suggestPosX = [
    38, 98, 158, 218, 278, 338, 398, 458, 518
];

var suggestPosY = [
    38, 98, 158, 218, 278, 338, 398, 458, 518
];

function getPositionFromLocation(lo) {
    var x = suggestPosX[lo.x];
    var y = suggestPosY[lo.y];
    return {
        'x': x,
        'y': y
    };
}

function getPieceAtLocation(lo) {
    for (var i = 0; i < com.pieces.length; i++) {
        if (com.pieces[i].isMyLocation(lo)) {
            return com.pieces[i];
        }
    }
}

function getLocationById(pieceId){
    for(var i = 0; i<com.pieces.length; i++){
        if(com.pieces[i].idPiece == pieceId){
            return com.pieces[i].mLocation;
        }
    }

    return null;
}

function cellContainPiece(lo) {
    if(lo.x>8 || lo.x<0 ||lo.y>8||lo.y<0){
        return false;
    }

    if (com.status[lo.x][lo.y] == 1) {
        return true;
    } else {
        return false;
    }
}

function LOG(message) {
    console.log(message);
}

function changePosServerToClient(loServer, myColor) {
    var newLocation = new Location(loServer.x, 8 - loServer.y);
    if (myColor == Blue) {
        return newLocation;
    } else if (myColor == Red) {
        newLocation.x = 8 - newLocation.x;
        newLocation.y = 8 - newLocation.y;
        return newLocation;
    }
}

function changePosClientToServer(loClient, myColor) {
    var lo = new Location(loClient.x, loClient.y);
    if (myColor == Red) {
        lo.x = 8 - lo.x;
        lo.y = 8 - lo.y;
    }

    var newLocation = new Location(lo.x, 8 - lo.y);
    return newLocation;
}

function testChangePos() {
    var locationServer = new Location(8, 8);
    var locationFromServerToClient = changePosServerToClient(locationServer, Red);
    LOG("location from server to client: " + locationFromServerToClient.x + ", " + locationFromServerToClient.y);
    var locationFromClientToServer = changePosClientToServer(locationFromServerToClient, Red);
    LOG("location from client to Server: " + locationFromClientToServer.x + ", " + locationFromClientToServer.y);
}

function drawSetting() {
    com.isSetting = true;
    com.setting.currentSetting = [];
    com.context.strokeStyle = "black";
    com.context.lineWidth = 2;
    com.context.font = 'bold 20px sans-serif';
    com.context.fillStyle = "#F3EADB";
    com.context.fillRect(140, 160, 300, 340);
    com.context.fillStyle = "black";
//    com.context.fillText("Setting", 255, 173);
//    com.context.beginPath();
//    com.context.rect(140, 190, 300, 360);
//    com.context.moveTo(140, 190);
//    com.context.lineTo(440, 190);
//    com.context.stroke();

    com.context.drawImage(com.settingHeader, 140, 100);
    com.context.drawImage(com.settingFooter, 140, 480);
    com.context.drawImage(com.settingLeft, 140, 164, 5, 317);
    com.context.drawImage(com.settingRight, 432, 164, 9, 317);
    com.context.drawImage(com.btnOk, 180, 450);
    com.context.drawImage(com.btnCancel, 300, 450);

    com.context.font = 'bold 15px sans-serif';
//    com.context.fillText("Thể loại", 150, 170);
    com.context.fillText("Thời gian tổng", 150, 210);
    com.context.fillText("Thời gian lượt đi", 150, 290);
    com.context.fillText("Điểm cược", 150, 370);

    com.context.font = 'bold 12px sans-serif';
//    com.context.fillText("Cờ chuẩn", 320, 190);
//    com.context.fillText("Cờ giản đơn", 170, 190);

    com.context.fillText("10  phút", 170, 230);
    com.context.fillText("15  phút", 170, 250);
    com.context.fillText("20  phút", 170, 270);
    com.context.fillText("25  phút", 320, 230);
    com.context.fillText("30  phút", 320, 250);
    com.context.fillText("60  phút", 320, 270);

    com.context.fillText("30  giây", 170, 310);
    com.context.fillText("01  phút", 170, 330);
    com.context.fillText("02  phút", 170, 350);
    com.context.fillText("05  phút", 320, 310);
    com.context.fillText("10  phút", 320, 330);
    com.context.fillText("15  phút", 320, 350);

    com.context.fillText("10  điểm", 170, 390);
    com.context.fillText("20  điểm", 170, 410);
    com.context.fillText("50  điểm", 170, 430);
    com.context.fillText("70  điểm", 320, 390);
    com.context.fillText("80  điểm", 320, 410);
    com.context.fillText("100 điểm", 320, 430);

    com.context.fillStyle = "#F3EADB";

//    for (var i = 0; i < settingType.length; i++) {
//        if (com.setting.type == settingType[i]) {
//            com.setting.currentSetting[3] = i;
//            drawRadio(typeType, i);
//        }
//    }

    for (var i = 0; i < settingTotalTime.length; i++) {
        if (com.setting.totalTime == settingTotalTime[i]) {
            com.setting.currentSetting[0] = i;
            drawRadio(typeTotal, i);
        }
    }

    for (var i = 0; i < settingTurnTime.length; i++) {
        if (com.setting.turnTime == settingTurnTime[i]) {
            com.setting.currentSetting[1] = i;
            drawRadio(typeTurn, i);
        }
    }

    for (var i = 0; i < settingMoney.length; i++) {
        if (com.setting.point == settingMoney[i]) {
            com.setting.currentSetting[2] = i;
            drawRadio(typeMoney, i);
        }
    }
}

//type la loai radio, co ba loai la radio tong time, radio turn time, va radio money
//pos la vi tri choose
var arrayPosSetting = [220, 300, 380, 180];
function drawRadio(type, pos) {

    //CLEAR GROUP RADIO BUTTON
    if(type == typeType){
        com.context.clearRect(250, arrayPosSetting[type], 20, 20);
        com.context.fillRect(250, arrayPosSetting[type], 20, 20);
        com.context.clearRect(400, arrayPosSetting[type], 20, 20);
        com.context.fillRect(400, arrayPosSetting[type], 20, 20);
    }else{
        com.context.clearRect(250, arrayPosSetting[type], 20, 50);
        com.context.fillRect(250, arrayPosSetting[type], 20, 50);
        com.context.clearRect(400, arrayPosSetting[type], 20, 50);
        com.context.fillRect(400, arrayPosSetting[type], 20, 50);
    }

    //reDraw group radioButton
    if(type == typeType){
        if(pos == 0){
            com.context.drawImage(com.radioOn, 250, arrayPosSetting[type], 15, 15);
            com.context.drawImage(com.radioOff, 400, arrayPosSetting[type], 15, 15);
        }else if(pos == 1){
            com.context.drawImage(com.radioOff, 250, arrayPosSetting[type], 15, 15);
            com.context.drawImage(com.radioOn, 400, arrayPosSetting[type], 15, 15);
        }
    }else{
        for (var i = 0; i < 3; i++) {
            if (i == pos) {
                com.context.drawImage(com.radioOn, 250, arrayPosSetting[type] + i * 20, 15, 15);
                com.context.drawImage(com.radioOff, 400, arrayPosSetting[type] + i * 20, 15, 15);
            } else if (i == pos % 3) {
                com.context.drawImage(com.radioOff, 250, arrayPosSetting[type] + i * 20, 15, 15);
                com.context.drawImage(com.radioOn, 400, arrayPosSetting[type] + i * 20, 15, 15);
            } else {
                com.context.drawImage(com.radioOff, 250, arrayPosSetting[type] + i * 20, 15, 15);
                com.context.drawImage(com.radioOff, 400, arrayPosSetting[type] + i * 20, 15, 15);
            }
        }
    }

    com.setting.currentSetting[type] = pos;
}

function clearSetting() {
    com.isSetting = false;
    com.context.clearRect(140, 80, 300, 424);
    drawStartButton();
}

function radioClick(mouseClick) {
    if ((mouseClick.y >= 450 && mouseClick.y <= 490)) {
        LOG("button click listener");
        if ((mouseClick.x >= 180 && mouseClick.x <= 280)) {
            LOG("button ok click");
            clearSetting();
            //TODO send setting to server
            var param = {};
            param.total = settingTotalTime[com.setting.currentSetting[0]];
            param.turn = settingTurnTime[com.setting.currentSetting[1]];
            param.point = settingMoney[com.setting.currentSetting[2]];
            //setting type chess simple or standard
//            param.type = settingType[com.setting.currentSetting[3]];
            sfs.send(new SFS2X.Requests.System.ExtensionRequest(command.setting, param));

        } else if ((mouseClick.x >= 300 && mouseClick.x <= 400)) {
            LOG("button cancel click");
            clearSetting();
        }
        return;
    }

    if ((mouseClick.x >= 250 && mouseClick.x <= 270) || (mouseClick.x >= 400 && mouseClick.x <= 420)) {
        var type;
        var diffY;
        var pos;
        if(mouseClick.y >=180 && mouseClick.y<=200){
            type = typeType;
            diffY = mouseClick.y - 180;
        }else if (mouseClick.y >= 220 && mouseClick.y <= 280) {
            type = typeTotal;
            diffY = mouseClick.y - 220;
        } else if (mouseClick.y >= 300 && mouseClick.y <= 360) {
            type = typeTurn;
            diffY = mouseClick.y - 300;
        } else if (mouseClick.y >= 380 && mouseClick.y <= 440) {
            type = typeMoney;
            diffY = mouseClick.y - 380;
        }

        pos = Math.floor(diffY / 20);
        if ((mouseClick.x >= 400 && mouseClick.x <= 420)) {
            if(type == typeType){
                pos += 1;
            }else{
                pos += 3;
            }
        }

        if (com.setting.currentSetting[type] != pos) {
            LOG("pos: " + pos);
            drawRadio(type, pos);
        }

        return;
    }
}

function drawFinishGame(isWin){
    if(isWin){
        com.context.drawImage(com.winImage, 120, 230);
    }else{
        com.context.drawImage(com.loseImage, 120, 230);
    }
}

function restartGame(){
    com.isSelected = false;
    com.isSetting = false;
    com.isPlay = false;
    com.score.blue = 0;
    com.score.red = 0;
    com.winRound1 = null;
    com.winRound2 = null;

    com.context.clearRect(0, 0, 560, 560);
    if(com.geos!=null){
        for(var i = 0; i< com.geos.length; i++){
            var lisPieceHit = com.geos[i];
            for(var j = 0; j<lisPieceHit.length; j++){
                LOG("piece hit Id: "+ lisPieceHit[j]);
                var loHighLight = getLocationById(lisPieceHit[j]);
                if(loHighLight!=null){
                    removeHighLight(loHighLight);
                }
            }
        }
        com.geos = null;
    }

//    newGame();
    reInitGame();
    if(com.myColor == Blue){
        drawStartButton();
    }else{
        drawReadyButton();
    }

    drawGButton(Blue, 0, 0);
    drawGButton(Red, 0, 0);
    updateSetting();
}